package com.example.loginpilot_01.util;

import com.example.loginpilot_01.entity.User;
import com.example.loginpilot_01.service.user.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

//@Component
public class EncryptOldPasswords implements CommandLineRunner {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    // 注入依赖
    public EncryptOldPasswords(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public void run(String... args) throws Exception {
        // 遍历所有用户，加密明文密码
        for (User user : userRepository.findAll()) {
            String rawPassword = user.getPassword();
            // 避免重复加密（BCrypt密文以$2a$开头）
            if (!rawPassword.startsWith("$2a$")) {
                user.setPassword(passwordEncoder.encode(rawPassword));
                userRepository.save(user);
            }
        }
        System.out.println("历史密码加密完成！");
    }
}